package ug.co.icom.kyazze.healthticket.services;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import ug.co.icom.kyazze.healthticket.data.QueryBuilder;
import ug.co.icom.kyazze.healthticket.mongoHQ.ObjectIDSearch;
import android.app.IntentService;
import android.content.Intent;

public class IntentMRecordService extends IntentService {
	private final static String TAG = "IntentMRecordService";
	File directory;

	public IntentMRecordService() {
		super(TAG);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		ApplicationObject mApplication = (ApplicationObject)getApplicationContext();
		
		try {
			long user_value = mApplication.getphone_number();
			File directory = mApplication.getDirectory();

			Random r = new Random();
			int Low = 10;
			int High = 1000;
			int R = (r.nextInt(High - Low) + Low);

			String random_identifier = String.valueOf(R);
			QueryBuilder qb = new QueryBuilder();
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost request = new HttpPost(qb.buildMedicalRecordsQuery());
			StringEntity params = new StringEntity(String.format(
					"{\"document\"  : {\"random_tag\": \"%s\", "
							+ "\"allergies\": [], \"conditions\": [], "
							+ "\"imaging\": [], \"immunizations\": [], "
							+ "\"lab\": [], \"medications\": [], "
							+ "\"surgery\": []}, \"safe\" : true}",
					random_identifier));

			request.addHeader("content-type", "application/json");
			request.setEntity(params);
			HttpResponse response = httpClient.execute(request);

			if (response.getStatusLine().getStatusCode() < 205) {
				ObjectIDSearch test = new ObjectIDSearch();
				Object val = test.getObjectID(random_identifier);
				String part1 = "{\"$oid\":";
				String part2 = "\"";
				String part3 = val.toString();
				String part4 = "\"}";
				@SuppressWarnings("unused")
				String mongolab = part1 + part2 + part3 + part4; // mongolab

				String Mongohq = val.toString();

				try {

					File file = new File(directory + "/", user_value + ".txt");
					BufferedWriter writer = new BufferedWriter(new FileWriter(
							file));
					writer.write(Mongohq);
					writer.newLine();
					writer.flush();
					writer.close();

				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		} catch (Exception e) {
			@SuppressWarnings("unused")
			String Error = TAG + " " + e.getMessage();
		}
	}

}
